package be.kafana.foursquare.down;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import be.kafana.foursquare.core.FourSquareAuthData;
import be.kafana.foursquare.core.GetWebResources;
import be.kafana.foursquare.down.data.Entity;
import be.kafana.foursquare.down.data.SearchResponse;
import be.kafana.foursquare.down.data.Venue;

import com.google.gson.Gson;

public class VenuesGrabber {

  private static final FourSquareAuthData data = new FourSquareAuthData();
  private Set<NameValuePair> queryParams = new HashSet<NameValuePair>();
  private BasicNameValuePair lastLocation = new BasicNameValuePair("ll",
      "42.00000,21.39000");

  public VenuesGrabber() {
    super();
    //TODO smarter way 
    initDefaults();
  }

  private void initDefaults() {
    String foodLikeVenuesID = "4d4b7105d754a06374d81259";

    queryParams.add(lastLocation);
    queryParams.add(new BasicNameValuePair("client_id", data.getClientId()));
    queryParams.add(new BasicNameValuePair("client_secret", data
        .getClientSecret()));
    queryParams.add(new BasicNameValuePair("v",
        new SimpleDateFormat("yyyyMMdd").format(new Date())));
    queryParams.add(new BasicNameValuePair("limit", "49"));
    queryParams.add(new BasicNameValuePair("radius", "4000"));
    queryParams.add(new BasicNameValuePair("categoryId", foodLikeVenuesID));

  }

  private SearchResponse grabDataFrom(double latitude, double longitude) {

    URI uri = null;
    try {
      // queryParams.remove(lastLocation);
      // lastLocation = new BasicNameValuePair("ll", String.valueOf(latitude)
      // + String.valueOf(longitude));
      // queryParams.add(lastLocation);
      uri = URIUtils.createURI("https", "api.foursquare.com", -1,
          "/v2/venues/search", URLEncodedUtils.format(
              new ArrayList<NameValuePair>(queryParams), "UTF-8"), null);

    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    GetWebResources conn = new GetWebResources();
    String json = null;
    try {
      json = conn.getContent(uri.toURL());
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    Entity res = new Gson().fromJson(json, Entity.class);
    return res.getResponse();
  }

  public static void main(String[] args) throws IOException, URISyntaxException {

    VenuesGrabber vg = new VenuesGrabber();
    SearchResponse res = vg.grabDataFrom(37.762573, -122.195435);

    for (Venue v : res.getVenues()) {
      System.out.println(v);

    }
  }

}
